//
//  NetWorkManager.swift
//  MQLWeibo
//
//  Created by MQL-IT on 2016/11/10.
//  Copyright © 2016年 MQL-IT. All rights reserved.
//

import UIKit
import Alamofire

enum RequestMethod {
    case GET
    case POST
}

class NetWorkManager: NSObject {

    static let shared = NetWorkManager()
    /// 访问令牌,所有网络请求都基于此令牌(登录除外)
    var accessToken: String? = "2.00Oly1mC1Ev5XBff62b8e0ef0_yGQq"
    
    func tokenRequest(url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters?, completion: @escaping (_ json : AnyObject?, _ isSuccess: Bool)->()) {
        guard let token = accessToken else {
            printLog(message: "没有token")
            completion(nil, false)
            return
        }
        var parameters = parameters
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"] = token
        requests(url: url, method: method, parameters: parameters, completion: completion)
    }
    
    func requests(url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters?, completion: @escaping (_ json : AnyObject?, _ isSuccess: Bool)->()) {
        let dataRequest: DataRequest = Alamofire.request(url, method: method, parameters: parameters, encoding: URLEncoding.default, headers: nil)
        
        dataRequest.responseJSON { (response ) in
            
            printLog(message: "请求的联接:\(response.request)")
            
            guard let value = response.result.value,
                response.result.error == nil else {
                printLog(message: "error:\(response.result.error)")
                    completion(nil, false)
                return
            }
            completion(value as AnyObject?, true)
        }
        
    }
    
}
